package com.example.ch03myrealmhiro.config;


import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();//标签方言
    }
    //记住我
    @Bean
    public CookieRememberMeManager getCookieRememberMeManager(){
        CookieRememberMeManager rememberMeManager = new CookieRememberMeManager();
        //需要设置cookie名字
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        //设置存活时间s
        cookie.setMaxAge(24*60*60);
        rememberMeManager.setCookie(cookie);
        return rememberMeManager;
    }

    @Bean
    //定义加密规则
    public HashedCredentialsMatcher getHashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //加密方式
        matcher.setHashAlgorithmName("md5");
        //循环次数
        matcher.setHashIterations(1);
        return matcher;
    }

    @Bean
    public Realm r(HashedCredentialsMatcher matcher){//自定义realm
        MyRealm realm = new MyRealm();
        //设置
        realm.setCredentialsMatcher(matcher);
        return realm;
    }

    @Bean
    public DefaultWebSecurityManager getD(Realm realm){
        DefaultWebSecurityManager default1 = new DefaultWebSecurityManager();
        default1.setRealm(realm);
        //向管理器中添加记住我
        default1.setRememberMeManager(this.getCookieRememberMeManager());
        return default1;
    }

    @Bean
    public ShiroFilterFactoryBean shiro1(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiro = new ShiroFilterFactoryBean();
        shiro.setSecurityManager(securityManager);
        Map<String,String> map=new HashMap();
        //添加拦截
        map.put("/","anon");
        map.put("/login","anon");
        map.put("/index.html","user");//记住我可以访问
        //authc登录访问
       // map.put("/register.html","anon");
        map.put("/exit","logout");//退出


        shiro.setFilterChainDefinitionMap(map);
        shiro.setUnauthorizedUrl("/login");
        return shiro;

    }
}
